package com.aijk.commons.group;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractGrouper<K, E> implements Grouper<K, E> {
    private List<E> elements = new ArrayList<E>();

    public AbstractGrouper(List<E> elements) {
        this.elements = elements;
    }

    @Override
    public GroupResults<K,E> group() {
        GroupResults<K,E> results = new GroupResults<K,E>();

        for (E element : elements) {
            K key = key(element);
            GroupResult<K,E> groupResult = results.getGroupResult(key);
            if (groupResult == null) {
                GroupResult<K,E> groupedResult = new GroupResult<K,E>(key);
                groupedResult.add(element);
                results.add(groupedResult);
            } else {
                groupResult.add(element);
            }
        }
        return results;
    }

    public abstract K key(E element);
}
